package cn.common;
import com.google.common.base.Strings;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.ContextLoader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by root on 17-1-20.
 */
public final class Helpers {
    //取WEB的根路径 ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/")
    /** 返回执行操作后的状态-success */
    public final static String SUCCESS = "success";

    public static void handleBindingResult(BindingResult bindingResult) {
        if (!bindingResult.hasErrors()) {
            return;
        }

        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : allErrors) {
            errorMsg.append(error.getDefaultMessage()).append("\n");
        }

        throw new CsbitException(errorMsg.toString());
    }

    public static String runSysCmd(String... command) {
        return run(true, null, command);
    }

    //路径基于脚本的当前路径
    //应用本身的脚本，放在classes下的子目录下【可以在这些目录下找子文件脚本，输出定向文件时不要在这】
    public static String runAppCmd(String... command){
        return runOwn(true, command);
    }
    public static void runAppCmdAsync(String... command){
        runOwn(false, command);
    }
    ////////
    private static String runOwn(boolean wait, String[] command) {
        File path = null;
        if(command.length>0){
            String f = Helpers.class.getResource("/").getPath() +  command[0];
            command[0] = f ;
            path = new File(f);
        }else
            assert(false);

        return run(wait, path.getParentFile(), command);
    }
    private static String run(boolean wait, File currentDir, String[] command) {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        StringBuilder processOutput = new StringBuilder();
        processBuilder.redirectErrorStream(true);
        if(currentDir != null)
            processBuilder.directory(currentDir);

        try {
            Process process = processBuilder.start();

            try (InputStreamReader in = new InputStreamReader(process.getInputStream());
                 BufferedReader processOutputReader = new BufferedReader(in);) {
                String readLine;
                while ((readLine = processOutputReader.readLine()) != null) {
                    processOutput.append(readLine + System.lineSeparator());
                }

                if(wait) {
                    process.waitFor();
                }
            }catch (InterruptedException i){
                Logger.error("processBuiler error wait:",i);
                throw new CsbitException("启动程序异常");
            }
        } catch (IOException e) {
            Logger.error("processBuiler error:", e);
            throw new CsbitException("启动程序异常");
        }

        return processOutput.toString();
    }
}
